<?php

if($_POST)
{
    $city = isset($_POST['city']) ? trim($_POST['city']) : '';

    $key = '9ab6176129dbb280b54721e4da1a1e78';

    $params = [
        'city' => $city,
        'key' => $key
    ];

    // 把请求参数转成url的参数格式
    $params = http_build_query($params);

    $ApiUrl = "http://apis.juhe.cn/simpleWeather/query?$params";

    $path = './data/' . $city . '.json';

    $time = 60 * 60;

    $now = time();

    $FileTime = 0;

    if(is_file($path))
    {
        $json = file_get_contents($path);

        $FileTime = filemtime($path);

        if(bcadd($FileTime,$time) < $now)
        {
            $json = file_get_contents($ApiUrl);
        }

    }else{
        $json = file_get_contents($ApiUrl);
    }

    $data = json_decode($json,true);

    if($data['error_code'] != 0)
    {
        echo json_encode(['code' => 0,'msg' => $data['reason'],'data' => null]);
        exit;
    }

    if(bcadd($FileTime,$time) < $now)
    {
        file_put_contents($path,$json);
    }

    echo json_encode(['code' => 1,'msg' => '查询成功','data' => $data]);
    exit;

    var_dump($data);
    exit;
}